package bg.btanev.eightyfour.service.impl;

import java.lang.Thread.State;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import bg.btanev.eightyfour.service.TargetService;
import bg.btanev.eightyfour.service.UpdateTargetService;
import bg.btanev.eightyfour.service.pooling.que.QueItem;
import bg.btanev.eightyfour.service.pooling.que.TargetsUpdateQue;

/**
 *
 * @author B.Tanev
 *
 */
public class UpdateTargetServiceImpl implements UpdateTargetService {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = LoggerFactory.getLogger(UpdateTargetServiceImpl.class);

	private TargetsUpdateQue targetsUpdateQue;
	private TargetService targetService;

	private Thread updateTargetsThread;

	public UpdateTargetServiceImpl() {
	}

	public void setTargetsUpdateQue(TargetsUpdateQue targetsUpdateQue) {
		this.targetsUpdateQue = targetsUpdateQue;
	}

	public void setTargetService(TargetService targetService) {
		this.targetService = targetService;
	}

	public void init() {
		logger.debug("init() - start"); //$NON-NLS-1$

		updateTargetsThread = new Thread(new Runnable() {
			@Override
			public void run() {
				QueItem queItem = null;

				while ((queItem = targetsUpdateQue.get()) != null) {
					try {
						targetService.updateTarget(queItem.getId());
					} catch (Exception e) {
						logger.error("Unhandled exception in the targets update deamon!", e); //$NON-NLS-1$
					}
				}

				logger.warn("Exiting targets update deamon...");
			}
		});
		updateTargetsThread.setDaemon(true);
		updateTargetsThread.start();
		logger.info("init() - Target update thread started."); //$NON-NLS-1$

		logger.debug("init() - end"); //$NON-NLS-1$
	}

	@SuppressWarnings("deprecation")
	public void destroy() {
		logger.debug("destroy() - start"); //$NON-NLS-1$

		if (updateTargetsThread != null) {
			if (State.TERMINATED.equals(updateTargetsThread.getState())) {
				updateTargetsThread.stop();
				updateTargetsThread = null;
			}
		}

		logger.debug("destroy() - end"); //$NON-NLS-1$
	}
}
